﻿
#define SPADAS_DEPRECATED_HIDE
#include "NextUtility.h"
#include "ffmpegdl.h"

namespace videonext
{
	Int searchNextNalu(Binary packet, Int startIndex)
	{
		for (Int i = startIndex; i < (Int)packet.size() - 4; i++)
		{
			if (packet[i] == 0 && packet[i + 1] == 0 && packet[i + 2] == 0 && packet[i + 3] == 1) return i + 4;
			else if (packet[i] == 0 && packet[i + 1] == 0 && packet[i + 2] == 1) return i + 3;
		}
		return -1;
	}
}

using namespace videonext;

void FFMPEG::enableLog()
{
	av_log_set_level(AV_LOG_VERBOSE);
}

void FFMPEG::disableLog()
{
	av_log_set_level(AV_LOG_QUIET);
}

OptionalBool Frame::isDependentFrameH264(Binary packet)
{
	if (packet.size() < 8) return OptionalBool();

	Int startIndex = 0;
	if (packet[0] == 0 && packet[1] == 0 && packet[2] == 0 && packet[3] == 1) startIndex = 4;
	else if (packet[0] == 0 && packet[1] == 0 && packet[2] == 1) startIndex = 3;
	else return OptionalBool();

	Byte targetByte = packet[startIndex];
	while (targetByte == 0x06) // SEI
	{
		startIndex = searchNextNalu(packet, startIndex);
		if (startIndex == -1) break;
		targetByte = packet[startIndex];
	}
	if (targetByte & 0x80) return OptionalBool();

	return (targetByte & 0x1F) != 7 && (targetByte & 0x1F) != 5;
}

OptionalBool Frame::isDependentFrameH265(Binary packet)
{
	if (packet.size() < 8) return OptionalBool();

	UInt startIndex = 0;
	if (packet[0] == 0 && packet[1] == 0 && packet[2] == 0 && packet[3] == 1) startIndex = 4;
	else if (packet[0] == 0 && packet[1] == 0 && packet[2] == 1) startIndex = 3;
	else return OptionalBool();

	Byte targetByte = packet[startIndex];
	if (targetByte & 0x80) return OptionalBool();

	UInt type = (targetByte & 0x7e) >> 1;
	if (type < 16) return TRUE;
	else if (type < 24) return FALSE;
	else if (type < 32) return TRUE;
	else if (type == 32) return FALSE;
	else return TRUE;
}